package utils;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

public class TreeNode {
    public int val;
    public TreeNode left;
    public TreeNode right;

    public TreeNode(int x) {
        val = x;
    }

    public TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }


    /**
     * 打印树
     * @return
     */
    public String printTree() {
        TreeNode root = new TreeNode(val,left,right);
        List<List<Integer>> result = new ArrayList<>();

        StringBuilder tree = new StringBuilder("[");

        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);

        while (!queue.isEmpty()) {
            int size = queue.size();
            tree.append("[");
            for (int i = 0; i < size; i++) {
                TreeNode node = queue.poll();
                if (node == null) tree.append("null,");
                else {
                    tree.append(node.val + ",");
                    queue.offer(node.left);
                    queue.offer(node.right);
                }
            }
            tree.deleteCharAt(tree.length() - 1);
            tree.append("]");
            tree.append( ",");
        }
        tree.deleteCharAt(tree.length() - 1);
        tree.append("]");
        return tree.toString();
        
        /*// 利用队列进行层序遍历

        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);

        while (!queue.isEmpty()) {
            int size = queue.size();
            List<Integer> currentLevel = new ArrayList<>();

            for (int i = 0; i < size; i++) {
                TreeNode node = queue.poll();
                if (node == null) currentLevel.add(null);
                else currentLevel.add(node.val);

                if (node != null) {
                    queue.offer(node.left);
                    queue.offer(node.right);
                }
            }

            result.add(currentLevel);
        }

        return result;*/
    }
}
